package com.atguigu.day08;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

public class Flink14_SQL_GroupWindow {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        // 2.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //设置本地时区
        Configuration configuration = tableEnv.getConfig().getConfiguration();
        configuration.setString("table.local-time-zone", "GMT");


        //TODO 3.在建表语句中指定事件时间字段
        tableEnv.executeSql("create table sensor(" +
                "id string," +
                "ts bigint," +
                "vc int," +
//                "et as to_timestamp(from_unixtime(ts/1000,'yyyy-MM-dd HH:mm:ss'))," +
                "et as to_timestamp_ltz(ts,3)," +
                "watermark for et as et - interval '3' second" +
                ") with("
                + "'connector' = 'filesystem',"
                + "'path' = 'input/sensor-sql.txt',"
                + "'format' = 'csv'"
                + ")"
        );

        //滚动窗口
/*        tableEnv.executeSql("select " +
                " id," +
                " sum(vc) as vcSum," +
                " tumble_start(et,interval '3' second) as wStart," +
                " tumble_end(et,interval '3' second) as wEnd" +
                " from sensor" +
                " group by " +
                " tumble(et,interval '3' second)," +
                " id" +
                "").print();*/

        //滑动窗口
        /*tableEnv.executeSql("select " +
                " id," +
                " sum(vc) as vcSum," +
                " hop_start(et,interval '2' second,interval '3' second) as wStart," +
                " hop_end(et,interval '2' second,interval '3' second) as wEnd" +
                " from sensor" +
                " group by " +
                " hop(et,interval '2' second,interval '3' second)," +
                " id" +
                "").print();*/
        //会话窗口
        tableEnv.executeSql("select " +
                " id," +
                " sum(vc) as vcSum," +
                " session_start(et,interval '2' second) as wStart," +
                " session_end(et,interval '2' second) as wEnd" +
                " from sensor" +
                " group by " +
                " session(et,interval '2' second)," +
                " id" +
                "").print();


    }
}
